<template>
  <div class="login-container">
    <!-- NavBar 组件：只需提供 title 标题 -->
    <van-nav-bar fixed title="黑马头条 - 登录" />
    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        label="手机号码"
        placeholder="请输入手机号码"
        required
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern: /^1\d{10}$/,
            message: '请填写正确的手机号',
            trigger: 'onBlur',
          },
        ]"
      />
      <van-field
        v-model="form.code"
        type="password"
        label="登录密码"
        placeholder="请输入登录密码"
        required
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '../../api/userAPI'
import { mapMutations } from 'vuex'

export default {
  name: 'Login',
  data () {
    return {
      form: {
        mobile: '',
        code: '246810'
      }
    }
  },
  methods: {
    ...mapMutations(['updateTokenInfo']),
    async onSubmit () {
      console.log(this.form)
      const { data: res } = await loginAPI(this.form)
      console.log(res)
      if (res.message === 'OK') {
        this.updateTokenInfo(res.data)

        // 登录成功后，跳转到主页
        if (this.$route.query.pre) {
          // 1. 如果携带了 pre 参数，则跳转到 pre 参数对应的路由地址
          this.$router.replace(this.$route.query.pre)
        } else {
          // 2. 如果没有 pre 参数，则直接跳转到 / 主页
          this.$router.push('/')
        }
      }
    }
  }
}
</script>

<style lang='less' scoped >
.login-container {
  padding-top: 46px;
}
</style>
